#include "Common.h"
#include "Application.h"
#include "GLGraphics.h"
#include "SDLInput.h"
#include "SDLTime.h"

#include <SDL/SDL.h>

namespace GenBen {

static uint globalWidth, globalHeight, globalScale;
static bool globalFullscreen, globalLcd;

GLGraphics* graphics = NULL;
SDLInput* input = NULL;
SDLTime* time = NULL;

void criticalError(string message)
{
	printf(message.c_str());
	SDL_Quit();
	exit(0);
}

Application::Application(const string& title, uint width, uint height, uint scale, bool fullscreen, bool lcd)
{
	ASSERT(width >= 320 && width <= 1600);
	ASSERT(height >= 240 && height <= 1200);
	ASSERT(scale >= 1 && scale <= 4);

	globalWidth = width;
	globalHeight = height;
	globalScale = scale;
	globalFullscreen = fullscreen;
	globalLcd = lcd;

	//Initialize SDL 
	if(SDL_Init(SDL_INIT_EVERYTHING) < 0 ) 
		criticalError("Unable to initialize SDL");
	
	SDL_WM_SetCaption(title.c_str(), NULL);

	time = new SDLTime();
}

Application::~Application()
{
	if(graphics) delete graphics;
	if(input) delete input;
	if(time) delete time;
	SDL_Quit();
}

void Application::run()
{
	bool quit = false;
	SDL_Event evt;

	init();

	while(!quit)
	{
		while(SDL_PollEvent(&evt)) 
		{ 
			if(input)
				if(input->process(evt))
					continue;

			//Handle user quit 
			if(evt.type == SDL_QUIT) 
				quit = true; 
		}

		time->update();

		if(input)
			input->update();

		update();
		render();
		
	}

	close();
}

Graphics* Application::getGraphics()
{
	if(graphics == NULL)
		graphics = new GLGraphics(globalWidth, globalHeight, globalScale, 0, globalFullscreen, globalLcd);

	return (Graphics*)graphics;
}

Input* Application::getInput()
{
	if(input == NULL)
		input = new SDLInput();

	return (Input*)input;
}

Time* Application::getTime()
{
	return (Time*)time;
}

}
